package slave

import (
	"backend/internal/common/errorx"
	"backend/internal/db/model"
	"context"
	"fmt"
	"net/http"

	"backend/internal/svc"
	"backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteSlaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteSlaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteSlaveLogic {
	return &DeleteSlaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteSlaveLogic) DeleteSlave(req *types.Slave) (resp *types.BaseResponse, err error) {
	var device = model.Device{}
	err = l.svcCtx.GormDB.Where("name =?", req.DeviceName).First(&device).Error
	if err != nil {
		errorStr := fmt.Sprintf("设备 %s 不存在!", req.DeviceName)
		logx.Errorf(errorStr)
		return nil, errorx.NewDefaultError(errorStr)
	}

	var slave = model.Slave{}
	err = l.svcCtx.GormDB.Where("device_id =? AND slave_id =?", device.ID, req.SlaveId).First(&slave).Error
	if err != nil {
		errorStr := fmt.Sprintf("从站 %d 不存在!", req.SlaveId)
		logx.Errorf(errorStr)
		return nil, errorx.NewDefaultError(errorStr)
	}

	err = l.svcCtx.GormDB.Delete(&slave).Error
	if err != nil {
		errorStr := fmt.Sprintf("删除设备 %s 从站: %v 失败!", req.DeviceName, req.SlaveId)
		logx.Errorf(errorStr)
		return nil, errorx.NewDefaultError(errorStr)
	}

	return &types.BaseResponse{
		Status: http.StatusOK,
		Msg:    fmt.Sprintf("删除设备 %s 从站: %v 成功!", req.DeviceName, req.SlaveId),
		Data:   true,
	}, nil
}
